<?php
/**
 * @file name : banner.php
 * @package   : thokim
 * @author    : Vo Thanh Minh
 * @email     : <thanhminhld@yahoo.com - thanhminhld@gmail.com>
 * @copyright : 2011
 *
 */
if (!defined('BASEPATH')) {
    exit('No direct script access');
}

class Banner extends Base_Controller
{
    /**
     * __construct
     * @access public
     * @param
     * @return
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
      * _remap
      * @access public
      * @param
      * @return
      */
    public function _remap( $method )
    {
        switch ($method) {

            case 'add':
            case 'edit':
                $this->addEditBanner();
                break;

            case 'save':
                $this->saveBanner();
                break;

            case 'del':
                $this->delBanner();
                break;

            default:
                $this->index();
        }
    }
    /**
     * @function index
     * @access     private
     * @param
     * @return
     */
    private function index()
    {
        $controlName    = $this->input->get_post('c');
        /**
         * Get message when save insert or edit submit
         *
         */
        $msgBoxDisp = '';
        $clsType    = '';
        $clsIcon    = '';

        $messages = $this->getErrMsg($msgBoxDisp, $clsType, $clsIcon);
        /**
         * Config for paging
         */
        $arrWhere = array('banner_show' => 'Y');
        $this->load->library('pagination');
        $config['base_url'] = 'http://' . $_SERVER["HTTP_HOST"] . dirname($_SERVER["SCRIPT_NAME"])
                            . '/?c=' . $controlName;
        $totalRows = $this->banner_model->getTotalRows($arrWhere);
        $config['total_rows'] = $totalRows;
        $config['per_page'] = 10;
        $config['num_links'] = 2;
        $config['page_query_string'] = TRUE;

        $config['first_link'] = 'First';
        $config['last_link'] = 'Last';
        $config['next_link'] = 'Next';
        $config['prev_link'] = 'Previous';
        $config['cur_tag_open'] = '&nbsp;<font color=#FF0000><strong>';
        $config['cur_tag_close'] = '</strong></font>';

        $this->pagination->initialize($config);
        $str_paging = $this->pagination->create_links();
        $this->msmarty->assign('paging',$str_paging);

        $offset = isset($_GET['per_page']) ? $_GET['per_page'] : 0;
        /**
         * End paging
         */
        $modulesList = $this->banner_model->loadList($arrWhere, $config['per_page'], $offset);
		$imgPath = UPLOAD_PATH . $controlName . '/';
        $data = array('urlControlName'  => '?c=' . $controlName,
                      'modulesList'     => $modulesList,
					  'imgPath'			=> $imgPath,
                      'messages'        => $messages,
                      'clsType'         => $clsType,
                      'clsIcon'         => $clsIcon,
                      'msgBoxDisp'      => $msgBoxDisp);

        $this->msmarty->view($controlName . '/admin.banner_manage', $data);
    }
    /**
     * @function addEditBanner
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param
     * @return
     */
    private function addEditBanner()
    {
        $controlName = $this->input->get_post('c');

        $category_id  = $this->input->get_post('category_id');
        /**
         * Your code addedit here
         */
        $data = array('actionForm'      => '?c=' . $controlName . '&m=save',
					  'category_id'		=> $category_id);

        $this->msmarty->view($controlName . '/admin.banner_addedit', $data);
    }
    /**
     * @function saveBanner
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param
     * @return
     */
    private function saveBanner()
    {
        $controlName    = $this->input->get_post('c');
        if ($_SERVER['REQUEST_METHOD']==='POST') {

			$category_id = $this->input->post('category_id');
			$data['banner_show'] = $this->input->post('showImg');
			if ($category_id > 0) {
				$fUpdate       = true;
				$data['id']  = $category_id;
			} else {
				$fUpdate       = false;
			}
			/**
			 * Load lang to show msg
			 */
			$this->lang->load('success', $this->lang_tag);
			$this->lang->load('error', $this->lang_tag);
			if (isset($_FILES['banner_img']['name'])) {
				$response = $this->do_upload('banner_img');
                if ($response['status'] == 'Error') {
                    defaultPage($controlName);
                }
				if ($response['resize_status'] == 'Error') {
					defaultPage($controlName);
				}
				$data['banner_img']		 = $response['file_name'];
				$data['banner_img_resz'] = $response['resize_name'];
            }
			///// Start transaction /////
			/////////////////////////////
			$this->db->trans_begin();

			$ret = $this->banner_model->storeTblWithoutLang($data, 'id', $fUpdate);

			if ($ret == FALSE) {
			    $this->messages->add($this->lang->line('db_insert_update_err'), 'error');
			    // Rollback transaction
			    $this->db->trans_rollback();
			} else {

                if ($fUpdate) {
                    $this->messages->add($this->lang->line('db_update_success'), 'success');
                } else {
                    $this->messages->add($this->lang->line('db_insert_success'), 'success');
                }
                // Commit transaction
                $this->db->trans_commit();
			}

        }
        defaultPage($controlName);
    }
    /**
     * @function delBanner
     *
     * @author      Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access     private
     * @param
     * @return     void
     */
    private function delBanner()
    {
        $controlName  = $this->input->get_post('c');
		$category_id  = $this->input->get_post('category_id');
		$imgPath = UPLOAD_PATH . $controlName . '/';
		$this->lang->load('success', $this->lang_tag);
		$this->lang->load('error', $this->lang_tag);

		if ( ! is_numeric($category_id) || $category_id <= 0) {
			$this->messages->add($this->lang->line('value_stranfer_err'), 'error');
			defaultPage($controlName);
		}
		$arrBanner = $this->banner_model->loadRecord($category_id);
		foreach($arrBanner as $bannerObj) {
			if (file_exists($imgPath . $bannerObj->banner_img)) {
				unlink($imgPath . $bannerObj->banner_img);
			}
			if (file_exists($imgPath . $bannerObj->banner_img_resz)) {
				unlink($imgPath . $bannerObj->banner_img_resz);
			}
		}
		$this->banner_model->deleteTbl(array('id' => $category_id), 'id');
		$this->messages->add($this->lang->line('db_delete_success'), 'success');
		defaultPage($controlName);
    }
    /**
     * @function getErrMsg
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param    string $msgBoxDisp, $clsType, $clsIcon
     * @return   array
     */
    private function getErrMsg(&$msgBoxDisp, &$clsType, &$clsIcon)
    {
        $messages = $this->messages->get();

        if (!is_array($messages)) {
            $messages = array();
            $msgBoxDisp = 'none;';
        } else {
            foreach($messages as $type => $message) {
                if(!empty($message)) {
                    if ($type == 'error') {
                        $clsType = $type;
                        $clsIcon = 'errorIcon';
                    } else if ($type == 'success') {
                        $clsType = $type;
                        $clsIcon = 'successIcon';
                    }
                    break;
                }
            }
        }
        $this->messages->clear();
        return $messages;
    }
    /**
     * @function do_upload
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param    string $imgFieldName
     * @return   Array
(
    [status] => Success
    [error] =>
    [file_name] => Bilitis_-_Guitar.mp3
    [file_type] => audio/mpeg
    [file_path] => /opt/lampp/htdocs/chuanghiemquang/application/uploads/songmusic/
    [full_path] => /opt/lampp/htdocs/chuanghiemquang/application/uploads/songmusic/Bilitis_-_Guitar.mp3
    [raw_name] => Bilitis_-_Guitar
    [orig_name] => Bilitis_-_Guitar.mp3
    [file_ext] => .mp3
    [file_size] => 1969.05
    [is_image] =>
    [image_width] =>
    [image_height] =>
    [image_type] =>
    [image_size_str] =>
)
     */
    private function do_upload($imgFieldName = '')
    {
        $response = array('status' => '',
                          'error'  => '');
        if ( ! is_string($imgFieldName) || strlen($imgFieldName) <= 0) {
            return $response = array('status' => 'Error',
                                     'error'  => '');
        }
        $controlName = $this->input->get_post('c');
        if (is_string($controlName) && strlen($controlName) > 0 &&
            function_exists('realpath') && @realpath(UPLOAD_PATH . $controlName) == FALSE) {
            mkdir(UPLOAD_PATH . $controlName, 0777);
        }
        if ($_SERVER['REQUEST_METHOD']==='POST') {
            $config['upload_path']   = UPLOAD_PATH . $controlName;
            $config['allowed_types'] = 'jpg|jpeg';
            $config['encrypt_name']  = FALSE;
            $this->load->library('upload', $config);

            if( !$this->upload->do_upload($imgFieldName) ) {
                $response['status'] = 'Error';
                $response['error'] = $this->upload->display_errors();

            } else {
                $response['status'] = 'Success';
                $data = $this->upload->data();
                $response = array_merge($response, $data);

                $file_name = $response['file_name'];
                $file_name = substr($file_name, strrpos($file_name, " "));
                /* This config for resize image */
                $configReZ['image_library'] = 'gd2';
                $configReZ['create_thumb']  = TRUE;
                $configReZ['width']         = '440';
                $configReZ['height']        = '142';
                $configReZ['master_dim']    = 'auto';
                $configReZ['source_image']  = UPLOAD_PATH . $controlName . '/' . $file_name;
                $this->load->library('image_lib', $configReZ);

                $response['resize_status']  = '';
                $response['resize_err']     = '';
                $response['resize_name']    = '';
                if (! $this->image_lib->resize()) {
                    $response['resize_status']    = 'Error';
                    $response['resize_err'] = $this->image_lib->display_errors() . $configReZ['source_image'];
                } else {
                    $response['resize_status']    = 'Success';
                    $ext = substr($file_name, strrpos($file_name, "."));
                    $file_name = substr($file_name, 0, strrpos($file_name, '.'));
                    $response['resize_name'] = $file_name . '_thumb' . $ext;
                }
            }
        }
        return $response;
    }
}
?>